package com.cloudcc.mobile.view.activity;

import java.util.ArrayList;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.Bind;
import butterknife.OnClick;
import butterknife.OnItemClick;

import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.net.ErrorInfo;
import com.cloudcc.cloudframe.net.ResultCallBack;
import com.cloudcc.cloudframe.ui.viewgroup.refresh.PtrDefaultHandler;
import com.cloudcc.cloudframe.ui.viewgroup.refresh.PtrFrameLayout;
import com.cloudcc.cloudframe.ui.viewgroup.refresh.PtrHandler;
import com.cloudcc.cloudframe.ui.viewgroup.refresh.header.DefaultMaterialHeader;
import com.cloudcc.cloudframe.ui.viewgroup.refresh.header.MaterialHeader;
import com.cloudcc.cloudframe.util.DensityUtils;
import com.cloudcc.cloudframe.util.ListUtils;
import com.cloudcc.cloudframe.util.StringUtils;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.ExtraConstant;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.ReceiverConstant;
import com.cloudcc.mobile.adapter.MultipleListAdapter;
import com.cloudcc.mobile.dao.impl.ApprovalEngineImpl;
import com.cloudcc.mobile.entity.MultipleListmodel;
import com.cloudcc.mobile.entity.beau.BeauInfoEntity;
import com.cloudcc.mobile.entity.beau.BeauInfoEntity.ObjMenu;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.util.PopuWindowUtils;
import com.cloudcc.mobile.util.ViewUtils;
import com.cloudcc.mobile.view.base.BaseActivity;
import com.cloudcc.mobile.view.web.CloudWebViewActivity;
import com.cloudcc.mobile.view.web.WebSyncDefaultProxy;
import com.cloudcc.mobile.view.web.WebSyncDefaultProxy.MonitorParam;
import com.cloudcc.mobile.weight.EmptyLayout;
import com.cloudcc.mobile.widget.CloudCCTitleBar;
import com.google.gson.JsonObject;

/**
 * 自定义列表内容显示activity
 * 
 * @author lhy 2015/11
 */

public class CreateMultipleListActivity extends BaseActivity implements
		PtrHandler, ResultCallBack<MultipleListmodel> {
	private ApprovalEngineImpl engine = new ApprovalEngineImpl();
	private MultipleListAdapter mAdapter;
	private String layoutId;// 布局id
	private String recordId;// 记录id
	private String relatedlistId;// 相关列表id
	private String prefix;// 对象标识
	private EmptyLayout empty_loading;
	private BeauInfoEntity mBeauInfo;
	private List<ObjMenu> objMenulist = new ArrayList<BeauInfoEntity.ObjMenu>();
	private String ACTION = ReceiverConstant.RECEIVE_REFRESH;
	@Bind(R.id.listview)
	ListView mListView;

	@Bind(R.id.headerbar)
	CloudCCTitleBar headerbar;
	@Bind(R.id.left_image)
	ImageView backbtn;
	@Bind(R.id.right_text)
	TextView rightplus;
	@Bind(R.id.right_image)
	ImageView rightimg;
	@Bind(R.id.load_more_list_view_ptr_frame)
	PtrFrameLayout mRefreshLayout;

	@Override
	public void init(Bundle savedInstanceState) {
		super.init(savedInstanceState);
		initHeader();
		initAdapter();
		initRefresh();
		initRequestData();
		empty_loading = new EmptyLayout(mContext);
		empty_loading.setLayoutParams(new LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		ViewUtils.addListViewEmptyView(mContext, mListView, empty_loading);
		empty_loading.empty();
		initReceiver();
	}

	/**
	 * 初始化 header 等参数
	 */
	private void initHeader() {
		Intent intent = getIntent();
		layoutId = intent.getStringExtra("layoutId");
		recordId = intent.getStringExtra("recordId");
		relatedlistId = intent.getStringExtra("relatedlistId");
		objMenulist = (List<ObjMenu>) getIntent().getSerializableExtra(
				"objMenulist");
		prefix = intent.getStringExtra("prefix");
		headerbar.setTitle(intent.getStringExtra("name"));
		backbtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				CreateMultipleListActivity.this.finish();
			}
		});
		if (objMenulist.size() == 1) {
			headerbar.setRightText("新建");
		} else if (objMenulist.size() == 0) {
			rightplus.setVisibility(View.GONE);
			rightimg.setVisibility(View.GONE);
		} else {
			headerbar.setRightImageResource(R.drawable.em_add);
		}
	}
	@OnItemClick(R.id.listview)
	public void itemclick(AdapterView<?> arg0, View arg1, int arg2,
			long arg3){
			Intent intent = new Intent(mContext, BeauInfoActivity.class);
			intent.putExtra("beau.name",
					TextUtils.isEmpty(objApiNameTilte) ? ""
							: objApiNameTilte);
			StringBuffer t = mAdapter.getItem(arg2);
			String[] textarr = t.toString().split(";");
			intent.putExtra("beau.id", textarr[textarr.length - 1]);
			if (StringUtils.equalsIgnoreCase(prefix, "001")) {
				intent.putExtra("beau.nameid", "account");
			} else if (StringUtils.equalsIgnoreCase(prefix, "002")) {
				intent.putExtra("beau.nameid", "opportunity");
			} else if (StringUtils.equalsIgnoreCase(prefix, "003")) {
				intent.putExtra("beau.nameid", "contact");
			} else if (StringUtils.equalsIgnoreCase(prefix, "004")) {
				intent.putExtra("beau.nameid", "lead");
			}else if(StringUtils.equalsIgnoreCase(prefix, "bda")){
				intent.putExtra("beau.nameid", "attachement");
			} else {
				intent.putExtra("beau.nameid",
						TextUtils.isEmpty(objApiNameId) ? "" : objApiNameId);
			}
			startActivity(intent);
	}

	/**
	 * 初始化刷新
	 */
	protected void initRefresh() {
		mRefreshLayout.setLoadingMinTime(1000);
		mRefreshLayout.setPtrHandler(this);
		final MaterialHeader header = new DefaultMaterialHeader(this);
		int[] colors = getResources().getIntArray(R.array.google_colors);
		header.setColorSchemeColors(colors);
		header.setLayoutParams(new PtrFrameLayout.LayoutParams(-1, -2));
		header.setPadding(0, DensityUtils.dpToPixel(mContext, 10), 0,
				DensityUtils.dpToPixel(mContext, 5));
		header.setPtrFrameLayout(mRefreshLayout);
		mRefreshLayout.setHeaderView(header);
		mRefreshLayout.addPtrUIHandler(header);
		mRefreshLayout.setResistance(5.0f);
	}

	/**
	 * 自动开启刷新请求数据
	 */
	private void initRequestData() {
		mRefreshLayout.postDelayed(new Runnable() {
			@Override
			public void run() {
				mRefreshLayout.autoRefresh(true);
			}
		}, 150);
	}

	private void initAdapter() {
		mAdapter = new MultipleListAdapter(mContext);
		mListView.setAdapter(mAdapter);
	}

	/**
	 * 刷新数据
	 */
	private void refreshData() {
		JsonObject jsonObject = new JsonObject();
		jsonObject.addProperty("layoutId", layoutId);
		jsonObject.addProperty("recordId", recordId);
		jsonObject.addProperty("relatedlistId", relatedlistId);
		headerbar.beginProgress();
		engine.GetMultipleRequest(jsonObject, this);
	}

	@Override
	public int getLayoutId() {
		return R.layout.create_multiple_list_layout;
	}

	@Override
	public boolean checkCanDoRefresh(PtrFrameLayout arg0, View arg1, View arg2) {
		return PtrDefaultHandler.checkContentCanBePulledDown(arg0, mListView,
				arg2);
	}

	@Override
	public void onRefreshBegin(PtrFrameLayout arg0) {
		refreshData();
	}

	@Override
	public void onFailure(ErrorInfo arg0) {
		headerbar.completeProgress();
		Toast.makeText(CreateMultipleListActivity.this, arg0.getErrorMessage(),
				Toast.LENGTH_LONG).show();
	}

	private String objApiNameId = "";
	private String objApiNameTilte = "";

	@Override
	public void onSuccess(MultipleListmodel data) {
		headerbar.completeProgress();
		mRefreshLayout.refreshComplete();
		List<StringBuffer> textlist = new ArrayList<StringBuffer>();
		List<JsonObject> valuelist = data.getRelationData();
		List<JsonObject> lablelist = data.getRelationFieldList();
		objApiNameId = data.relationObjId;
		objApiNameTilte = data.relationObjLabel;
		//lablelist  所有的每条记录的行数
		//valuelist  所有的记录 条数
		for (JsonObject vauleObject : valuelist) {// 确定每条数据有几行
			StringBuffer textobj = new StringBuffer();
			for (JsonObject jsonObject : lablelist) {
				String title =jsonObject.get("label").getAsString();
				String bridge ="/:";
				String apiKey =jsonObject.get("name").getAsString();
				if (isTypeC(jsonObject.get("type").getAsString())) {//是不是m
					apiKey +="ccname";
				}
				boolean jsonNull = vauleObject.get(apiKey).isJsonNull();
				String value =jsonNull?"":vauleObject.get(apiKey).getAsString();
				String text = title+bridge+ value;
				textobj.append(text + ";");
			}
			
			if (textobj != null) {
				textobj.append(vauleObject.get("id").getAsString());
				textlist.add(textobj);
			}
			
		}
		if (textlist.size() < 1) {
			empty_loading.empty();
		}
		mAdapter.changeData(textlist);
	}

	public class MyItem {
		public List<SubItem> mlist;
		public class SubItem {
			public String title;
			public String value;
		}
	}
	

	private boolean isTypeC(String type) {
		for (String iterable_element : types) {
			if (StringUtils.equalsIgnoreCase(iterable_element, type)) {
				return true;
			}
		}
		return false;
	}

	private final String[] types = new String[] { "Y", "M", "R" };

	@OnClick(R.id.right_text)
	public void clicktext() {
		ObjMenu objMenu = objMenulist.get(0);
		Intent intent = new Intent(mContext, CloudWebViewActivity.class);
		intent.putExtra(
				ExtraConstant.EXTRA_URL,
				UrlManager.getManager().addReturnUrl(
						UrlManager.getManager().getUrlByRoot(
								objMenu.relationUrl)));
		MonitorParam monitorParam = new MonitorParam(new String[]{"m=save","m=query","type=remark"},
				WebSyncDefaultProxy.STEP_START, new String[] {
						"/WeiXin_index.action", "m=query" }, true,
				WebSyncDefaultProxy.STEP_OVERRIDEURL);
		intent.putExtra(
				"callback",
				WebSyncDefaultProxy.creatDefaultProxy(ACTION)
						.addMonitorParam(monitorParam).addHomeMonitor());
		startActivity(intent);
	}

	private PopupWindow mRightMenu;

	@OnClick(R.id.right_image)
	public void clicknew() {
		showRightPopu();
	}

	private void showRightPopu() {
		if (objMenulist == null || ListUtils.isEmpty(objMenulist)) {
			return;
		}
		PopuWindowUtils.dissmiss(mRightMenu);
		View contentView = (View) View.inflate(mContext,
				R.layout.layout_popu_container, null);
		LinearLayout subContainer = (LinearLayout) contentView
				.findViewById(R.id.pop_holder);
		final int excNum = objMenulist.size() > 3 ? 3 : objMenulist.size();
		int popuHeight = 0;
		for (int i = 0; i < objMenulist.size(); i++) {
			View containerView = View.inflate(mContext,
					R.layout.layout_pop_item, null);
			ImageView ivLogo = (ImageView) containerView
					.findViewById(R.id.pop_item_image);
			ivLogo.setVisibility(View.GONE);
			TextView tvTitle = (TextView) containerView
					.findViewById(R.id.pop_item_text);
			ImageView LIne = (ImageView) containerView
					.findViewById(R.id.item_line);
			popuHeight += ViewUtils.getViewMeasuredHeight(containerView);
			if (i > 3 && i != objMenulist.size() + 2) {
				containerView.setVisibility(View.GONE);
			}
			ivLogo.setImageResource(R.drawable.entity_right_menu);
			ObjMenu objMenu = objMenulist.get(i);
			tvTitle.setText(objMenu.relationName);
			containerView.setOnClickListener(new MyMenuClick(i));
			subContainer.addView(containerView);
		}
		mRightMenu = new PopupWindow(contentView, AppContext.screenW / 3,
				ViewGroup.LayoutParams.WRAP_CONTENT);
		mRightMenu.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
		mRightMenu.setFocusable(true);
		mRightMenu.showAsDropDown(rightimg);

	}

	private class MyMenuClick implements OnClickListener {

		private int mPosition;

		public MyMenuClick(int position) {
			super();
			this.mPosition = position;
		}

		@Override
		public void onClick(View v) {
			if (mPosition < objMenulist.size()) {
				PopuWindowUtils.dissmiss(mRightMenu);
				ObjMenu objMenu = objMenulist.get(mPosition);
				Intent intent = new Intent(mContext, CloudWebViewActivity.class);
				intent.putExtra(
						ExtraConstant.EXTRA_URL,
						UrlManager.getManager().addReturnUrl(
								UrlManager.getManager().getUrlByRoot(
										objMenu.relationUrl)));
				MonitorParam monitorParam = new MonitorParam(
						new String[] {"m=save","m=query","type=remark"},
						WebSyncDefaultProxy.STEP_START, new String[] {
								"/WeiXin_index.action", "m=query"}, true,
						WebSyncDefaultProxy.STEP_OVERRIDEURL);
				intent.putExtra("callback", WebSyncDefaultProxy
						.creatDefaultProxy(ACTION)
						.addMonitorParam(monitorParam).addHomeMonitor());
				startActivity(intent);
			}
		}
	};

	private SyncReceiver mSyncReceiver;

	private void initReceiver() {
		mSyncReceiver = new SyncReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(ACTION);
		mContext.registerReceiver(mSyncReceiver, filter);
	}

	private class SyncReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			initRequestData();
		}
	}

	@Override
	public void onDestroy() {
		if (mSyncReceiver != null) {
			mContext.unregisterReceiver(mSyncReceiver);
		}
		EventEngine.uregister(this);
		super.onDestroy();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		initRequestData();
	}
	
}
